package backend

import (
	"awesome-devops/applications/backend/middlewares"
	"awesome-devops/applications/backend/modules/handlers"
	"fmt"
	"gitee.com/jjawesomejj/awesome-util/config"
	"gitee.com/jjawesomejj/awesomehttp/boot"
	awesomehttp "gitee.com/jjawesomejj/awesomehttp/system"
	"gitee.com/jjawesomejj/awesomehttp/system/helper"
	"gitee.com/jjawesomejj/awesomehttp/system/httpContext"
	"net/http"
	"reflect"
	"strconv"
)

func RunHttpServer() {
	route := boot.DefaultApp()
	route.ResourcePath = "dist"
	portString := config.GetConfigByKey("httpPort", func() interface{} {
		return "80"
	}).(string)
	portInt, err := strconv.Atoi(portString)
	if err != nil {
		panic("httpPort need string params")
	}
	route.Port = float64(portInt)
	route.Group([]awesomehttp.Middleware{&middlewares.AuthMiddleware{}, &middlewares.GlobalMiddleware{}}, "/api", func() {
		route.RegisterModule(func() awesomehttp.HttpHandler {
			return &handlers.ProjectHandler{}
		})
		route.RegisterModule(func() awesomehttp.HttpHandler {
			return &handlers.DeployHandler{}
		})
		route.RegisterModule(func() awesomehttp.HttpHandler {
			return &handlers.ServerConfigHandler{}
		})
		route.RegisterModule(func() awesomehttp.HttpHandler {
			return &handlers.RunnerHandler{}
		})
		route.RegisterModule(func() awesomehttp.HttpHandler {
			return &handlers.AccountHandler{}
		})
	})
	route.Group([]awesomehttp.Middleware{&middlewares.GlobalMiddleware{}}, "", func() {
		route.RegisterModule(func() awesomehttp.HttpHandler {
			return &handlers.UserHandler{}
		})
		route.RegisterModule(func() awesomehttp.HttpHandler {
			return &handlers.WebHookHandler{}
		})
	})
	route.Group([]awesomehttp.Middleware{&middlewares.AuthMiddleware{}}, "", func() {
		route.RegisterModule(func() awesomehttp.HttpHandler {
			return &handlers.ApiHandler{}
		})
	})
	route.RegisterModule(func() awesomehttp.HttpHandler {
		return &handlers.DownloadHandler{}
	})

	route.AddRoute(awesomehttp.Route{
		Router:        "/test",
		RequestMethod: awesomehttp.REQUEST_METHOD_GET,
		RunFun: func(ctx *httpContext.HttpContext) interface{} {
			return "v8"
		},
	})
	route.ErrAction = func(w http.ResponseWriter, r *http.Request, err error) {
		w.Header().Add("Access-Control-Allow-Origin", "*") //允许访问所有域
		tool := awesomehttp.ReflectTool{}
		if tool.MethodExist(err, "BaseError") {
			data := tool.CallFunByName(err, "BaseError").([]reflect.Value)
			w.Write([]byte(data[0].String()))
			return
		} //处理自定义错误
		fmt.Println(helper.PrintStackTrace(err))
		w.WriteHeader(500)

		w.Write([]byte(helper.JsonEncode(map[string]interface{}{
			"code": 500,
			"msg":  "awesome-devops 无法处理此请求",
		})))
	}

	route.Listen()
}
